package App.OO.ClientView;

import App.Model.Interface.MessageType;
import App.Model.Tool.DosTool;
import App.Model.Tool.SwingUtil;
import App.Model.User;
import App.Model.message.Message;
import App.OO.service.OOLoginSignService;
import App.OO.service.thread.CtoSThread;
import App.OO.service.thread.Manage.ManageCtoSThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Objects;

//OO第一次注册的页面(此处逻辑性较弱,考虑重构(改为service,界面在OOLoginView中实现))
public class OOSignFrame extends JFrame {
    private User user = new User();
    private Socket socket = null;

    public boolean OOSign() {//由于代码设置,创建完成后就会自动登录
        showSignFrame();
        System.out.println("请输入你的账号: ");
        String userId = DosTool.readString(20);
        System.out.println("请输入你的密码: ");
        String userPsw = DosTool.readString(20);
        System.out.println("再次确定你的密码:");
        String userPsw_ = DosTool.readString(20);
        if (!userPsw.equals(userPsw_)) {
            System.out.println("两次密码不统一,请重新注册");
        } else {
            user.setUserId(userId);
            user.setPassword(userPsw);
            user.setUserName("注册");
            //发送到服务端进行账号唯一性检测

            try {
                socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);//域名随服务器更换
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                //发送user到服务端
                outputStream.writeObject(user);

                //读取从服务端回复的Message信息
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) inputStream.readObject();

                if (message.getMesType().equals(MessageType.MESSAGE_SIGN_SUCCEED)) {//注册成功成功
                    //创建一个和服务器端始终保持联系的线程
                    System.out.println("注册成功 " + userId);
                    //为主窗口提供一个临时创建的OOLoginSignService
                    OOLoginSignService signService = new OOLoginSignService();
                    signService.setSocket(socket);
                    signService.setUser(user);
                    OOMainFrame mainFrame = new OOMainFrame(signService);
                    mainFrame.showMainFrame();//打开窗口
                    CtoSThread ctosThread = new CtoSThread(socket, mainFrame);
                    ctosThread.start();
                    ManageCtoSThread.addCtoSThread(userId, ctosThread);
                    return true;
                } else {//登录失败,关闭socket
                    System.out.println("注册失败,用户ID已被占用");
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public User getUser() {
        return user;
    }

    public Socket getSocket() {
        return socket;
    }

    //登录窗口的绘制
    public void showSignFrame() {
        Font textFont = new Font("宋体", Font.BOLD, 17);
        setTitle("OO注册");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        //底部注册与登录按钮
        JPanel PanelSough = new JPanel(new FlowLayout());
        JButton signButton = new JButton("注册");
        signButton.setFont(textFont);
        signButton.setPreferredSize(new Dimension(100, 25));
        PanelSough.add(signButton);

        //程序icon标
        setIconImage(new ImageIcon("src\\main\\resources\\recourse\\OO.png").getImage());

        //顶部OO图标
        JPanel PanelNorth = new JPanel(new FlowLayout());
        JLabel ooLabel = new JLabel();
        int width = 63, height = 72;
        ImageIcon image = SwingUtil.createAutoAdjustIcon("src\\main\\resources\\recourse\\OO.png", false);//实例化ImageIcon 对象
        //image.setImage(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT ));
        ooLabel.setIcon(image);
        ooLabel.setPreferredSize(new Dimension(width, height));
        PanelNorth.add(ooLabel);

        //中间账号与密码输入框
        JPanel panelCenter = new JPanel(new FlowLayout());
        JPanel panelCenter_one = new JPanel(new FlowLayout());
        JPanel panelCenter_tow = new JPanel(new FlowLayout());
        JPanel panelCenter_thr = new JPanel(new FlowLayout());
        JLabel mention = new JLabel("                                               ");
        JTextField userId = new JTextField("Arisu", 22);
        JPasswordField userPsw = new JPasswordField("1230", 22);
        userPsw.setEchoChar('●');//隐藏密码
        userId.setCaretPosition(userId.getText().length());//光标移至末尾
        JLabel jLabel = new JLabel("账号: ");
        jLabel.setFont(textFont);
        JLabel jLabel_ = new JLabel("密码: ");
        jLabel_.setFont(textFont);
        JLabel jLabel__ = new JLabel("确认密码");
        jLabel__.setFont(textFont);

        //添加显示密码的按钮
        JButton toggleButton = new JButton("●");
        toggleButton.setFont(new Font("像素字体", Font.BOLD, 10));
        toggleButton.setPreferredSize(new Dimension(18, 20));
        toggleButton.addActionListener(new ActionListener() {
            boolean isPasswordVisible = false;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isPasswordVisible) {
                    userPsw.setEchoChar('●'); // 隐藏密码
                } else {
                    userPsw.setEchoChar((char) 0); // 显示密码
                }
                isPasswordVisible = !isPasswordVisible;
            }
        });

        panelCenter_one.add(jLabel);
        panelCenter_one.add(userId);
        panelCenter_one.add(new JLabel("     "));
        panelCenter_tow.add(jLabel_);
        panelCenter_tow.add(userPsw);
        panelCenter_tow.add(toggleButton);
        panelCenter_thr.add(mention);
        panelCenter.add(panelCenter_one);
        panelCenter.add(panelCenter_tow);
        panelCenter.add(panelCenter_thr);

        //事件处理
        userId.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (userId.getCaret() != null && !Objects.equals(userId.getText(), "")) {
                        userPsw.requestFocusInWindow(); // 请求焦点到第二个文本框
                        userPsw.setCaretPosition(userPsw.getPassword().length);//光标移至末尾
                    }
                }
            }
        });
        userPsw.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (userPsw.getCaret() != null && !userPsw.getText().equals("") && !Objects.equals(userId.getText(), "")) {

                    } else {
                        if (userPsw.getText().equals("")) {
                            mention.setText("   请输入密码   ");
                        } else if (!Objects.equals(userId.getText(), "")) {
                            mention.setText("   请输入账号   ");
                        }
                    }
                }
            }
        });
        signButton.addActionListener(e -> {//跳转注册页面
            //注册行为发送到服务器,判断注册是否合法
        });

        //布局
        setLayout(new BorderLayout());
        add(PanelSough, BorderLayout.SOUTH);
        add(PanelNorth, BorderLayout.NORTH);
        add(panelCenter, BorderLayout.CENTER);

        setVisible(true);                                 //使窗体可视
        setBounds(400, 300, 400, 300);    //设置窗体显示位置和大小
        //frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
